//
//  OAuthViewController.swift
//  SinaBlog
//
//  Created by ChenWei on 15/10/10.
//  Copyright © 2015年 cw. All rights reserved.
//

import UIKit
import SVProgressHUD

class OAuthViewController: UIViewController {
    let wbAppKey = "1082570401"
    let wbAppSecret = "18d91b3cac188412ffa58721d3f6a279"
    let wbReDirectURL = "http://www.baidu.com"
    
    override func loadView() {
        view = webView
        webView.delegate = self;
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        // 1.设置导航条
        navigationItem.title = "新浪微博"
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "关闭", style: UIBarButtonItemStyle.Plain, target: self, action: Selector("close"))
        
        // 2.设置背景颜色
        view.backgroundColor = UIColor.whiteColor()
        
        // 3.加载登录界面,获取授权Request Token
        let str = "https://api.weibo.com/oauth2/authorize?client_id=" + wbAppKey + "&redirect_uri=" + wbReDirectURL
        let url = NSURL(string: str)!
        let request = NSMutableURLRequest(URL: url)
        webView.loadRequest(request)
    }
    
   @objc private func close() {
        dismissViewControllerAnimated(true, completion: nil)
    }
    
    // MARK: -懒加载
    private  var webView = UIWebView()
}

extension OAuthViewController: UIWebViewDelegate {
    func webViewDidStartLoad(webView: UIWebView) {
        SVProgressHUD.showSuccessWithStatus("正在加载登陆界面......", maskType: SVProgressHUDMaskType.Black)
    }
    
    func webViewDidFinishLoad(webView: UIWebView) {
        SVProgressHUD.dismiss()
    }
    
    // 每次webview发送请求时调用,返回true代表可以访问,返回false代表不能访问
    func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        NSLog("%@", request)
        /*
        登陆界面:  https://api.weibo.com/oauth2/authorize?client_id=1082570401&redirect_uri=http://www.baidu.com
        授权界面:  https://api.weibo.com/oauth2/authorize
        已经授权:  http://www.baidu.com/?code=103c97a322ee51c9690339b5e7394fb6
        取消授权: http://www.baidu.com/?error_uri=%2Foauth2%2Fauthorize&error=access_denied&error_description=user%20denied%20your%20request.&error_code=21330
        无论是授权成功还是取消授权, 都应该关闭授权界面
        */
        
        // 1.判断是否跳转到微博对应的界面
        let URLStr = request.URL!.absoluteString
        if !URLStr.hasPrefix(wbReDirectURL) {
            return true
        }
        
        // 2.判断是否是跳转到授权回调页
        let codeStr = "code="
        if !URLStr.containsString("error") {
            NSLog("已经授权")
//            NSLog(  request.URL!)
            // 2.1截取"code="后面的字符串
            let code = request.URL!.query!.substringFromIndex(codeStr.endIndex)
            NSLog(message: code)
            // 2.2利用已经授权的RequestToken换取AccessToken
            loadAccessToken(code)
        } else {
            NSLog(  "取消授权")
            // 2.2
            close()
        }
        
        return false;
    }
    
    // 获取AccessToken
    private func loadAccessToken(code:String) {
        // 1.定义URL地址
        let path = "oauth2/access_token"
        
        // 2.定义参数
        let parames = ["client_id": wbAppKey, "client_secret": wbAppSecret, "grant_type": "authorization_code", "code" :code , "redirect_uri":wbReDirectURL ];
        
        // 3.利用AFN发送网络请求
        NetworkTools.shareNetworkTools().POST(path, parameters: parames, success: { (_, dict) -> Void in
            
            // 3.1将字典转化为模型
            let account = UserAccount(dict: dict as! [String : AnyObject])
            
            // 3.2加载用户信息
            account.loadUserInfo({ (account,error) -> () in
                if account != nil {
                    // 保存授权信息
                    account?.saveAccount()
                    // 发送通知更改根控制器->进入"首页"控制器
                    NSNotificationCenter.defaultCenter().postNotificationName(CWSwitchRootViewControllerNotify, object: nil)
                    return
                }
                SVProgressHUD.showErrorWithStatus("获取用户授权失败", maskType: SVProgressHUDMaskType.Black)
            })
            
            }) { (_, error) -> Void in
                SVProgressHUD.showErrorWithStatus("获取用户授权失败", maskType: SVProgressHUDMaskType.Black)
                
                print(error)
        }
    }
}



